label_list
len(label_list)
label_list
len(label_list)

##---(Sun Jul 16 13:34:09 2017)---
import numpy as np
a=np.zeros([10,8])
a[1][1]
a[0][0]
a[:,0]
a[:,9]
a[:,8]
a=[1,2]
a=np.array(a)
a=[[1,2,3],[1,2,3]]
a=np.asarray(a,dtype='float32')
test=[a,a]
test=np.asarray(test,dtype='float32')
L=[1,2,3,4]
L.remove(L[1])
L
"""
Created on Fri Jul  7 09:06:36 2017

@author: WANGWEIW23
"""
from PIL import Image
import os
import pandas as pd
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
def eachFile(filepath):
    filelist2=[]
    pathDir = os.listdir(filepath)
    pathDir_pic=[]
    for files in pathDir:
        pathDir_pic.append(os.path.splitext(files)[0])
    for allDir in pathDir:
        child = os.path.join('%s%s%s' % (filepath,'/', allDir))
        filelist2.append(child)
       # .decode('gbk')是解决中文显示乱码问题
    return filelist2,pathDir_pic


def filepath(mainpath="D:\\Users\\WANGWEIW23\\Desktop\\UNBC\\Images"):
    path1=os.listdir(mainpath)
    directory1=[]
    for i in range(len(path1)):
        if path1[i][0]!='.':
           directory1.append(os.path.join(mainpath,path1[i]))
    directory2=[]
    for i in range(len(directory1)):
        path2=os.listdir(directory1[i])
        for j in range(len(path2)):
            if path2[j][0]!='.':
               directory2.append(os.path.join(directory1[i],path2[j]))
    picdirec=[]
    for i in range(len(directory2)):
        path3=os.listdir(directory2[i])
        for j in range(len(path3)):
            if path3[j][0]!='.':
               picdirec.append(os.path.join(directory2[i],path3[j]))
    return picdirec 


picdirec=filepath(mainpath="D:\\Users\\WANGWEIW23\\Desktop\\UNBC\\Images")
indirec=filepath(mainpath="D:\\Users\\WANGWEIW23\\Desktop\\UNBC\\Frame_Labels\\FACS")
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/prepross.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x=datafile(picdirec)
x=range(0,10)
for x in range(0,10):
    print(x)
for x in range(1,10):
   print(x)
(10,23,12)==(10,22,12)

##---(Mon Jul 17 13:57:49 2017)---
L=['alla','12','qww']
L.remove(L[1])
L
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/prepross.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
y=labelfile(indirec)

##---(Tue Jul 18 11:09:27 2017)---
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/prepross.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x=datafile(picdirec)

##---(Tue Jul 18 14:59:39 2017)---
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/prepross.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
picdirec[1]
y=labelfile(indirec)
y[:,0]
y[:,0].shape
label_result=np.zeros([48398,13])
type(label_result)
label_result[0,:]
a=[[1,2],[2,3]]
y[1]
y[1][0]
y[2][0]

##---(Thu Jul 20 20:05:33 2017)---
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
[a][b][c]="abc"
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')

##---(Fri Jul 21 15:45:23 2017)---
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
im.size
type(im.size)
im.resize((128,128))
im=im.resize((128,128))
im.show()
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')

##---(Sun Jul 23 01:22:29 2017)---
import keras
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/model.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
model
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/model.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
import numpy as np
import pandas as pd
from PIL import Image
import os
from pandas import Series,DataFrame
def datafile(picdirec):
    x=[]
    for i in range(len(picdirec)):
        try:
            im=Image.open(picdirec[i])
        except:
            continue
        im.load()
        pixes=np.asarray(im,dtype='float32')
        x.append(pixes)
    return x    

picdirec='D:\output\immul'
x=datafile(picdirec)
im=Image.open(picdirec+'1_det_0.bmp')
im=Image.open(picdirec+'\1_det_0.bmp')
im=Image.open(picdirec+'\'+'1_det_0.bmp')
im=Image.open(picdirec+'\\'+'1_det_0.bmp')
len(picdirec)
path=os.listdir(picdirec)
path[1]
len(path)
path[1]
picdirec+path[1]
picdirec+'\\'+path[1]
path=[picdirec+'\\'+path[i] for i in range(len(parth))]
path=[picdirec+'\\'+path[i] for i in range(len(path))]
len(path)
picdirec
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x=datafile(picdirec)
x[1].size
x[1].shape
size(x[1])
Size(x[1])
x[1].size
x[1].shape
type(x[1].shape)
[(1,2,3),(2,3,4)]
test=[(1,2,3),(2,3,4)]
dict_num = dict((i,words.count(i)) for i in set(test))
dict_num = dict((i,test.count(i)) for i in set(test))
test=[(1,2,3),(2,3,4),(1,2,3)]
dict_num = dict((i,test.count(i)) for i in set(test))
x[1].append(1)
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x=datafile(picdirec)
x[1][1]
x[1,1]
x[:][1]
type(x[:][1])
len(x[:][1])
len(x[:][0])
(x[:][0])
(x[:][1])
(x[:][0])
x[:][1]
x[1][1]
x[0][1]
x[:][1]
x[1][1]
x[:][0]
dict_num
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,dict_num=datafile(picdirec)
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,dict_num=datafile(picdirec)
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,dict_num=datafile(picdirec)
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,dict_num=datafile(picdirec)
os.path.splittext('c:\\csv\\test.csv')
os.path.splitext('c:\\csv\\test.csv')
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,dict_num=datafile(picdirec)
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,dict_num=datafile(picdirec)
x[1].shape
dict.values
dict.values()
dict(334, 350, 3)
dict((334, 350, 3))
dict{(334, 350, 3)}
max(dict_num)
dict_num[334, 350, 3]
dict=sorted(dic_num.item(),key=lambda d:d[1],reverse=True)
dict=sorted(dict_num.item(),key=lambda d:d[1],reverse=True)
dict=sorted(dict_num.items(),key=lambda d:d[1],reverse=True)
dict[1]
type(dict[1])
dict[1][1]
dict[1][0]
type(dict[1][0])
dict[1][0]
dict[0][0]
x[1]
x[1].format
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,x_resized=datafile(picdirec)
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x=[]
for i in range(len(path)):
    try:
        im=Image.open(path[i])
    except:
        continue
    im.load()
    pixes=np.asarray(im,dtype='float32')
    x.append(pixes)
shape_list=[]
for i in range(len(x)):
      shape_list.append(x[i].shape)
    
path=os.listdir(picdirec)
path=[picdirec+'\\'+path[i] for i in range(len(path))]
x=[]
for i in range(len(path)):
    try:
        im=Image.open(path[i])
    except:
        continue
    im.load()
    pixes=np.asarray(im,dtype='float32')
    x.append(pixes)
shape_list=[]
for i in range(len(x)):
    shape_list.append(x[i].shape)
    
set(shape_list)
dict_num=dict((i,shape_list.count(i)) for i in set(shape_list))
dict=sorted(dict_num.items(),key=lambda d:d[1],reverse=True)
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,x_resized=datafile(picdirec)
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,x_resized=datafile(picdirec)
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,x_resized=datafile(picdirec)
debugfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
img_size=dict[0][0]
x_resized=[]
for i in range(len(path)):
    try:
        im=Image.open(path[i])
        im=im.resize(img_size)
    except:
        continue
    im.load
    pixes=np.asarray(im,dtype='float32')
    x_resized.append(pixes)
    
path=os.listdir(picdirec)
path=[picdirec+'\\'+path[i] for i in range(len(path))]

x_resized=[]
for i in range(len(path)):
    try:
        im=Image.open(path[i])
        im=im.resize(img_size)
    except:
        continue
    im.load
    pixes=np.asarray(im,dtype='float32')
    x_resized.append(pixes)
    
x_resized=[]
for i in range(len(path)):
    try:
        im=Image.open(path[i])
        im=im.resize(img_size)
    except:
        continue
    im.load()
    pixes=np.asarray(im,dtype='float32')
    x_resized.append(pixes)
    
im=Image.open(path[1])
im.load()
im.size
im=Image.open(path[2])
im.size
im=Image.open(path[3])
im.size
im.resize(img_size)
img_size
img_size[1]
img_size[1][2]
img_size[0]
img_size[0:1]
img_size[0:2]
im.resize(img_size[0:2])
im
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,x_resized=datafile(picdirec)
x[1]
x[1].resize((338,350,3))
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,x_resized=datafile(picdirec)
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,x_resized=datafile(picdirec)
x=(1,2)
x[1]
(x[1],x[0])
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,x_resized=datafile(picdirec)
im
path=os.listdir(picdirec)
path=[picdirec+'\\'+path[i] for i in range(len(path))]

im=Image.open(path[1])
type(im)
%varexp --hist path
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,x_resized=datafile(picdirec)
import tensorflow as tf
import keras
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/test.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
x,x_resized=datafile(picdirec)
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/prepross.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
picdirec1='D:\\output\\immul'
path=os.listdir(picdirec1)
path=[picdirec1+'\\'+path[i] for i in range(len(path))]

indirec[1].split("\\")[-1].split(".")[0]
picdirec[1]
def fib(max):
    n,a,b=0,0,1
    while n<max:
         print(b)
         a,b=b,a+b
         n=n+1
    return 'done'

fib(10)
def fib(max):
    n,a,b=0,0,1
    while n<max:
         yield b;
         a,b=b,a+b
         n=n+1
    return 'done'

fib(10)
a=fib(10)
a.next()
next(a)
def lazy_sum(*args):
    def sum():
        ax = 0
        for n in args:
            ax = ax + n
        return ax
    return sum

f=lazy_sum(1,3,5,7,9)
f
f()
import numpy as np
a=[2,3;2,3;3,4]
a=array([1,1,0,1,1,0,1,0])
a=np.array([1,1,0,1,1,0,1,0])
a=a.reshape([4,2])
b=np.array([0,0,1,0,1,1,0,0])
b=b.reshape([4,2])
a[1]
def count():
    def f(j):
        def g():
            return j*j
        return g
    fs = []
    for i in range(1, 4):
        fs.append(f(i)) 
    return fs

f1,f2,f3=count()
f1()
f2()
f3()
f1,f2,f3,f4=count()
f1,f2,f3=count()
list(map(lambda x:x*x,[1,2,3,4,5,6,7,8,9]))
def log(func):
    def wrapper(*args, **kw):
        print('call %s():' % func.__name__)
        return func(*args, **kw)
    return wrapper

@log
def now():
    print('2015-3-25')
    
now
now()
@log('execute')
def now():
    print('2015-3-25')
    
now()
@log('execute')
def now():
    print('2015-3-25')
    
a
a.shape[1]
a[1][1]
a[1]
a.T[1]
a.T[2]
a.T[0]
from sklearn.metrics import classification_report
for i in range(a.shape[1]):
    print(classification_report(a.T[i],b.T[i]))
    
type(a)
a[1][1]
type(a[1][1])
a
a=np.array([0.1,0.2,0.3,0.6,0.4,0.7,0.2,0.8])
a=a.reshape((4,2))
a.shape[0]
a.shape[1]
a[4][2]
a[3][2]
a[3][1]
a.shape[0]
a.shape[1]
for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        if a[i][j]>0.5:
            a[i][j]=1
        else a[i][j]=0
for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        if a[i][j]>0.5:
            a[i][j]=1
        else:
            a[i][j]=0
            
for i in range(a.shape[1]):
    classification_report(a.T[i],b.T[i])
    
for i in range(a.shape[1]):
    print(classification_report(a.T[i],b.T[i]))
    
for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        if a[i][j]>0.5:
            a[i][j]=1
        else:
            a[i][j]=0
            
a
b
a.shape[1]
a.T[1]
len(a.T[1])
for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        if a[i][j]>0.5:
            a[i][j]=1
        else:
            a[i][j]=0
            

a
a.shape[1]
for i in range(a.shape[1]):
    count=0;
    for j in range(len(a.T[i])):
        if a[j][i]==0:
           count=count+1
           
for i in range(a.shape[1]):
    count=0;
    for j in range(len(a.T[i])):
        if a[j][i]==0:
           count=count+1
    print(count/a.shape[1])
    
a
a.shape[1]
for i in range(a.shape[1]):
    count=0;
    for j in range(len(a.T[i])):
        if a[j][i]==0:
           count=count+1
    print(count/a.shape[0])
    
for i in range(a.shape[1]):
    count=0;
    for j in range(len(a.T[i])):
        if a[j][i]==0:
           count=count+1
    print(count/a.shape[0])
    
import keras
import theano
import utensorflow
list(map(lambda x:x*x,[1,2,3,4,5,6,7,8,9]))
f=lambda x:x*x
f
f(4)
def build(x,y):
    return lambda: x*x+y*y

build(3,2)
build(3,2)()
def f(x):
    return x*x

r=map(f,[1,2,3,4,5,6,7,8,9])
list(r)
L=[]
for i in [1,2,3,4,5,6,7,8,9]:
    L.append(f(i))
    
from functools import reduce
def add(x,y):
    return x+y

reduce(add,[1,3,5,7,9])
def is_odd(n):
    return n%2==1

list(filter(is_odd,[1,2,4,5,6,9.10.15]))
list(filter(is_odd,[1,2,4,5,6,9.10,15]))
def _odd_iter():
    n=1
    while True:
        n=n+
def _odd_iter():
    n=1
    while True:
        n=n+2
        yield n
        
_odd_iter()
_odd_iter()()
next(_odd_iter())
def _not_divisible(n):
    return lambda x:x%n>0

def primes():
    yield 2
    it=_odd_iter()
    while True:
        n=next(it)
        yield n
        it=filter(_not_divisible(n),it)
        
primes()
next(primes())
for n in primes():
    if n<100:
        print(n)
    else:
        break
    
for n in _odd_iter():
    if n<100:
        print(n)
    else:
        break
    
for n in _not_divisible():
    if n<100:
        print(n)
    else:
        break
    
_not_divisible(12)
_not_divisible(12)(13)
runfile('D:/Users/WANGWEIW23/.spyder-py3/face_action_unit/model.py', wdir='D:/Users/WANGWEIW23/.spyder-py3/face_action_unit')
import model
model.test()
import sys
sys.path
bart = Student('Bart Simpson', 98)
class Student(object):
    def __init__(self, name, score):
        self.__name = name
        self.__score = score

    def print_score(self):
        print('%s: %s' % (self.__name, self.__score))
        
bart = Student('Bart Simpson', 98)
bart.__name
bart.name
bart.score
class Student(object):
    def __init__(self, name, score):
        self.__name = name
        self.__score = score

    def print_score(self):
        print('%s: %s' % (self.__name, self.__score))
        
bart = Student('Bart Simpson', 98)
bart.name
bart.__name
bart.score
class Animal(object):
    def run(self):
        print('Animal is running...')
        
class Dog(Animal):
    pass

class Cat(Animal):
    pass

dog = Dog()
dog.run()

dir('ABC')
class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def print_score(self):
        print('%s: %s' % (self.name, self.score))
        
bart = Student('Bart Simpson', 98)
bart.name
bart.score
class Student(object):
    def __init__(self, name):
        self.name = name

s = Student('Bob')
s.score = 90

s = Student('Bob')
s.name
s.score
class Student(object):
    pass

s=Student()
s.name='nam'
s.name
from types import MethodType
def set_age(self,age):
    self.age=age
    
s.name
s
s.score
s.set_age = MethodType(set_age, s)
s.set_age(25)
s.age
s.name
class Student(object):
    __slots__ = ('name', 'age')
    
s=Student()
s.name='mick'
s.age=25
s.score=99
class GraduateStudent(Student):
    pass

g=GraduateStudent()
g.score=999
g.score
class Student(object):

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value
        
s=Student()
s.score
s.score=60
s.score
class Animal(object):
    pass

class Mammal(Animal):
    pass

class Runnable(object):
    def run(self):
        print('Running...')
        
class Dog(Mammal,Runnable):
    pass

class Fib(object):
    def __init__(self):
        self.a,self.b=0,1
    def __iter__(self):
        return self
    def __next__(self):
        self.a,self.b=self.b,self.a+self.b
        if self.a>100000
class Fib(object):
    def __init__(self):
        self.a,self.b=0,1
    def __iter__(self):
        return self
    def __next__(self):
        self.a,self.b=self.b,self.a+self.b
        if self.a>100000:
            raise StopIteration()
        return self.a
    
for n in Fib():
    print(n)
    
class Fib(object):
    def __getitem__(self,n):
        a,b=1,1
        for x in range(n):
            a,b=b,a+b
        return a
    
f=fib()
f=Fib()
f[12]
class Fib(object):
    def __getitem__(self,n):
       if isinstance(n int): 
         a,b=1,1
         for x in range(n):
             a,b=b,a+b
         return a
class Fib(object):
    def __getitem__(self,n):
       if isinstance(n,int): 
         a,b=1,1
         for x in range(n):
             a,b=b,a+b
         return a
     
class Fib(object):
    def __getitem__(self,n):
       if isinstance(n,int): 
         a,b=1,1
         for x in range(n):
             a,b=b,a+b
         return a
       if isinstance(n,slice):
          start=n.start
          stop=n.stop
          if start is None:
             start=0
          a,b=1,1
          L=[]
          for x in range(stop):
              if x>=start:
                  L.append(a)
              a,b=b,a+b
          return L


f=Fib()
f[0:5]
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
Month.Jan
Month.Feb
try:
    print('try...')
    r = 10 / 0
    print('result:', r)
except ZeroDivisionError as e:
    print('except:', e)
finally:
    print('finally...')
print('END')

try:
    print('try...')
    r = 10 / int('a')
    print('result:', r)
except ValueError as e:
    print('ValueError:', e)
except ZeroDivisionError as e:
    print('ZeroDivisionError:', e)
finally:
    print('finally...')
print('END')

try:
    print('try...')
    r = 10 / int('2')
    print('result:', r)
except ValueError as e:
    print('ValueError:', e)
except ZeroDivisionError as e:
    print('ZeroDivisionError:', e)
else:
    print('no error!')
finally:
    print('finally...')
print('END')

def foo(s):
    return 10 / int(s)

def bar(s):
    return foo(s) * 2

def main():
    try:
        bar('0')
    except Exception as e:
        print('Error:', e)
    finally:
        print('finally...')
        
main()
import logging
import logging

def foo(s):
    return 10 / int(s)

def bar(s):
    return foo(s) * 2

def main():
    try:
        bar('0')
    except Exception as e:
        logging.exception(e)
        
main()
from io import StringIO
f=StringIO()
f.write('hello')
from tkinter import *
from tkinter import *
import tkinter.messagebox as messagebox

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.nameInput = Entry(self)
        self.nameInput.pack()
        self.alertButton = Button(self, text='Hello', command=self.hello)
        self.alertButton.pack()

    def hello(self):
        name = self.nameInput.get() or 'world'
        messagebox.showinfo('Message', 'Hello, %s' % name)
        
app=Application()
app.master.title("hello world")
app.mainloop()
from datetime import datetime
now=datetime.now()
now
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
from collections import deque
q = deque(['a', 'b', 'c'])
from collections import defaultdict
dd = defaultdict(lambda: 'N/A')
import os
os.getcwd()
f=open('test.txt','r')
f=open('test1.txt','r')
f.read()
f.close()
f
try:
    f=open('test.txt','r')
    print(f.read())
finally:
    if f:
        f.close()
        
try:
    f=open('test1.txt','r')
    print(f.read())
finally:
    if f:
        f.close()
        
import pickle
data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}
selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)

output=open('test.pkl','wb')
pickle.dump(data1,output)
output.close()
import pprint,pickle
pkl_file=open('data.pkl','rb')
pkl_file=open('data.pkl','wb')
pkl_file=open('test.pkl','rb')
data1=pickle.load(pkl_file)
pprint.pprint(data1)
data2=pickle.load(pkl_file)
pkl_file
pkl_file.close()
from keras.utils.np_utils import to_categorical
int_labels=[1,2,3]
categorical_labels=to_categorical(int_labels,num_classes=None)
print(categorical_labels)
from keras import optimizers
model=Sequential()
from keras.layers import Sequential
from keras. import Sequential
from keras import Sequential
from keras.models import Sequential
model=Sequential()
model.add(Dense(64,init='unitform',input_shape=(10,)))
from keras.layers import Dense
model.add(Dense(64,init='unitform',input_shape=(10,)))
from keras.activations import softmax
from keras.activations import ReLU
from keras.activations import relu
from keras import initializers
from keras.layers.wrappers import TimeDistributed
model=Sequential()
model.add(TimeDistributed(Dense(8),input_shape=(10,16)))
model.output_shape
from keras.layers import Permute
model=Sequential()
model.add(Permute((2,1),input_shape=(10,64)))
model.out_put
model.output_shape
model.input_shape
from keras.layers import Reshape
model=Sequential()
model.add(Reshape((3,4),input_shape=(12,)))
model.input_shape
model.add(Reshape((-1,2,2)))
model.input_shape
model.output_shape
from keras.layers import Convolution2D
model=Sequential()
model.add(Convolution2D(64,3,3,border_mode='same',input_shape=(3,32,32)))
model.input_shape
model.output_shape
data1
with open('test1.pkl','wb') as file:
    pickle.dump(data1,file)
    
from keras.layers import LSTM
model=Sequential()
model.add(LSTM(32,input_shape=(10,64)))
model.output_shape
model.input_shape
model.add(LSTM(16))
model=Sequential()
model.add(LSTM(32,input_dim=64,input_length=10))
model.add(LSTM(16))
model.add(LSTM(16),return_sequences=True)
model.add(LSTM(16,return_sequences=True))
from keras.layers import Embedding
model=Sequential()
model.add(Embedding(1000,64,input_length=10))
model.input_shape
model.output_shape
input_array=np.random.randint(1000,size=(32,10))
input_array.shape
input_array.length
model=Sequential()
from keras.layers import Bidirectional
model.add(Bidirectional(LSTM(10,return_sequences=True),input_shape=(5,10)))
model.input_shape
model.output_shape
model.add(Bidirectional(LSTM(10)))
10%3
fs=[]
for i in range(13):
    f0=Sequential(name='f'+str(i))
    
f0
import json
class Student(object):
    def __init__(self,name,age,score):
        self.name=name
        self.age=age
        self.score=score
        
s = Student('Bob', 20, 88)
import os
print('Process(%s) start...'%os.getpid())
os.getpid()
pid=os.fork()
from multiprocessing import Process
import os
def run_proc(name):
    print 'Run child process %s (%s)...' % (name, os.getpid())
def run_proc(name):
    print('Run child process %s (%s)...' % (name, os.getpid()))
    
def run_proc(name):
    print('Run child process %s (%s)...' % (name, os.getpid()))

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Process(target=run_proc, args=('test',))
    print('Process will start.')
    p.start()
    p.join()
    print('Process end.')
    
def run_proc(name):
    print('Run child process %s (%s)...' % (name, os.getpid()))

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Process(target=run_proc, args=('test',))
    print('Process will start.')
    p.start()
    p.join()
    print('Process end.')
    
from multiprocessing import Pool
import os, time, random

def long_time_task(name):
    print('Run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('Task %s runs %0.2f seconds.' % (name, (end - start)))

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Pool()
    for i in range(5):
        p.apply_async(long_time_task, args=(i,))
    print('Waiting for all subprocesses done...')
    p.close()
    p.join()
    print('All subprocesses done.')
    
from multiprocessing import Process,Queue
# 写数据进程执行的代码:
def write(q):
    for value in ['A', 'B', 'C']:
        print 'Put %s to queue...' % value
        q.put(value)
        time.sleep(random.random())
# 写数据进程执行的代码:
def write(q):
    for value in ['A', 'B', 'C']:
        print('Put %s to queue...' % value)
        q.put(value)
        time.sleep(random.random())
        
def read(q):
    while True:
        value = q.get(True)
        print('Get %s from queue.' % value)
        

def write(q):
    for value in ['A', 'B', 'C']:
        print('Put %s to queue...' % value)
        q.put(value)
        time.sleep(random.random())

# 读数据进程执行的代码:
def read(q):
    while True:
        value = q.get(True)
        print('Get %s from queue.' % value)

if __name__=='__main__':
    # 父进程创建Queue，并传给各个子进程：
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    # 启动子进程pw，写入:
    pw.start()
    # 启动子进程pr，读取:
    pr.start()
    # 等待pw结束:
    pw.join()
    # pr进程里是死循环，无法等待其结束，只能强行终止:
    pr.terminate()
    
import time
import thread
import threading
threading.current_thread().name
import time
import threading
def loop():
    print('thread %s is running...' % threading.current_thread().name)
    n = 0
    while n < 5:
        n = n + 1
        print('thread %s >>> %s' % (threading.current_thread().name, n))
        time.sleep(1)
    print('thread %s ended.' % threading.current_thread().name)

print('thread %s is running...' % threading.current_thread().name)
t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join()
print('thread %s ended.' % threading.current_thread().name)

balance=0
lock=threading.Lock()
def run_thread(n):
    for i in range(10000):
        lock.acquire()
        try:
            change_it(n)
        finally:
            lock.release()
            
import threading,multiprocessing
multiprocessing.cpu_count()
def loop():
    x=0
    while True:
        x=x^1
        
for i in range(multiprocessing.cpu_count()):
    t=threading.Thread(target=loop)
    t.start()
    
import re
re.match(r'^\d{3}\-\d{3,8}$', '010-12345')

re.match(r'^\d{3}\-\d{3,8}$', '010 12345')
from collections import OrderedDict

d = dict([('a', 1), ('b', 2), ('c', 3)])

od=OrderedDict(d)
od
import itertools
natuals = itertools.count(1)
for n in natuals:
    print(n)
    

for key,group in itertools.groupby('AAABBBCCAAA'):
    print key,list(group)
for key,group in itertools.groupby('AAABBBCCAAA'):
    print(key,list(group))
    
import itertools
for key,group in itertools.groupby('AAABBBCCAAA'):
    print(key,list(group))
    
2
from xml.parsers.expat import ParserCreate
xml = r'''<?xml version="1.0"?>
<ol>
    <li><a href="/python">Python</a></li>
    <li><a href="/ruby">Ruby</a></li>
</ol>
'''

handler=DefaultSexHandler()
class DefaultSaxHandler(object):
    def start_element(self, name, attrs):
        print('sax:start_element: %s, attrs: %s' % (name, str(attrs)))

    def end_element(self, name):
        print('sax:end_element: %s' % name)

    def char_data(self, text):
        print('sax:char_data: %s' % text)
        
handler=DefaultSexHandler()
handler = DefaultSaxHandler()
parser = ParserCreate()
parser.returns_unicode = True
parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data
parser.Parse(xml)

handler = DefaultSaxHandler()
parser = ParserCreate()
parser.returns_unicode = True
parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data
parser.Parse(xml)

L = []
L.append(r'<?xml version="1.0"?>')
L.append(r'<root>')
L.append(encode('some & data'))
L.append(r'</root>')
return ''.join(L)
ns=itertools.repeat('A',10)
for n in ns:
    print(n)
    
import numpy as np
a=np.array([1,2,3,5])
a=a.reshape([2,2])
a[1][1]
a[1]
type(a[1])
a=a.reshape([1,4])
a.shape
a.shape[0]
a[1]
a[0]
max(a[0])
b=np.zeros([1,2])
b[1][1]
b[0][1]

##---(Fri Jul 28 17:30:51 2017)---
import keras

##---(Fri Jul 28 19:19:15 2017)---
import itertools
natuals=itertools.count(1)
9%2
from __future__ import print_function
ns=itertools.takewhile(lambda x:x<=10,natuals)
for n in ns:
    print(n)
    
for c in itertools.chain('ABC','XYZ')
for c in itertools.chain('ABC','XYZ'):
    print(c)
    
for key,group in itertools.groupby('AaaBBbcCAAa', lambda c: c.upper()):
    print(key,list(group))
    
for x in itertools.imap(lambda x,y:x*y,[10,20,30],itertools.count(1)):
    print(x)
    
from HTMLParser import HTMLParser
from wsgiref.simple_server import make_server
def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return '<h1>Hello, web!</h1>'

httpd = make_server('', 8000, application)
runfile('D:/Users/WANGWEIW23/server.py', wdir='D:/Users/WANGWEIW23')
self.sensors = [0 for x in xrange(5)]

self.sensors = [0 for x in range(5)]
stations = ['Schagen', 'Heerhugowaard', 'Alkmaar', 'Castricum', 'Zaandam', 'Amsterdam', 'Sloterdijk', 'Amsterdam Centraal', 'Amsterdam Amstel', 'Utrecht Centraal', '’s-Hertogenbosch', 'Eindhoven', 'Weert', 'Roermond', 'Sittard', 'Maastricht']
IndEind = stations.index(eindStation)
runfile('D:/Users/WANGWEIW23/server.py', wdir='D:/Users/WANGWEIW23')
a=[[1],[1,2],[1,2,3]];
b=pad_sequences(a,maxlen=3,padding='pre');
print(b,b.shape)
c=pad_sequences(a,maxlen=3,padding='post');
print(c,c.shape)

a=[[1],[1,2],[1,2,3]];
b=pad_sequences(a,maxlen=2,truncating='pre');
print(b,b.shape)
c=pad_sequences(a,maxlen=2,truncating='post');
print(c,c.shape)

runfile('D:/Users/WANGWEIW23/server.py', wdir='D:/Users/WANGWEIW23')
runfile('D:/Users/WANGWEIW23/server.py', wdir='D:/Users/WANGWEIW23')
c,b=test_pad_sequences()
couples,labels=skipgrams([0,1,2,3],vocabulary_size=4);
print("couples:",couples)
print("labels:",labels)

make_sampling_table(5)
from keras.layers import Embedding
from keras.models import Sequential
model=Sequential()
model.add(Embedding(1000,64,input_length=10))
model.input_dim
model.input_shape
model.output_shape
from keras.layers.wrappers import TimeDistributed
model=Sequential()
model.add(TimeDistributed(Dense(8),input_shape=(10,16)))
from keras.layers.wrappers import TimeDistributed,Dense
from keras.layers import Dense
model.add(TimeDistributed(Dense(8),input_shape=(10,16)))
model.input_shape
model.output_shape